/**
 * @Author: easten
 * @Created: 2024-07-31 23:13:22
 * @Description: 产品管理
 *
 */
import React, { useState, useEffect } from "react";
import ProductConfigDrawer from "./ProductConfigDrawer";
import { ModuleCommonProps, PageParams } from "_common/DataType";
import {
  Alert,
  Button,
  Descriptions,
  message,
  MessagePlugin,
  Popconfirm,
  Space,
  Switch,
  Table,
  Tag,
} from "tdesign-react";
import { TableTitle } from "components";
import { RefreshIcon } from "tdesign-icons-react";
import { IotAttr, IotDeviceGroup, IotSensorGroup } from "_common/entity";
import ProductDrawer from "./ProductDrawer";
import { TdDescriptionItemProps } from "tdesign-react/es/descriptions/type";
import { ApiDeviceGroup } from "_common/api/iot";
export type IotProductCompProps = ModuleCommonProps & {
  hideAdd?: boolean;
  hideEdit?: boolean;
  hideDel?: boolean;
};
const IotProductComp: React.FC<IotProductCompProps> = (
  props: IotProductCompProps
) => {
  const { axios, className, hideAdd, hideDel, hideEdit } = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([
    1, 2,
  ]);
  const [loading, setLoading] = useState<boolean>(false);
  const [userList, setGroupList] = useState<IotDeviceGroup[]>([]);
  const [selectedRow, setSelectedRow] = useState<IotDeviceGroup>();
  const [userName, setGroupName] = useState<string>();
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  const [pageState, setPageState] = useState<PageParams>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });

  const [visible, setVisible] = useState(false);
  const [configOpen, setConfigOpen] = useState(false);
  const [edit, setEdit] = useState(false);
  const apiDeviceGroup = new ApiDeviceGroup(axios);

  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  useEffect(() => {
    getGroupList();
  }, [userName]);

  const getGroupList = async () => {
    const response = await apiDeviceGroup.getPageList({
      ...pageState,
      userName,
    });
    if (response && response.code == 200 && response.data) {
      setGroupList(response.data.list);
      setPageState({
        ...pageState,
        total: response.data.total,
      });
    }
  };

  // 删除
  const deleteGroup = async (id: number) => {
    const response = await apiDeviceGroup.deleteDeviceGroup(id);
    if (response && response.code == 200 && response.data) {
      message.success("删除成功");
      getGroupList();
    }
  };

  const rehandleExpandChange = (value: any) => {
    setExpandedRowKeys(value);
  };

  const getItems = (row: IotSensorGroup) => {
    let items: TdDescriptionItemProps[] = [];
    items.push({
      label: "物模型名称",
      content: row?.groupName,
    });
    items.push({
      label: "物模型编码",
      content: row?.groupCode,
    });
    items.push({
      label: "物模型描述",
      content: row?.groupDesc,
    });
    return items;
  };

  // 获取物模型item
  const getAttrs = (attr: IotAttr) => {
    let items: TdDescriptionItemProps[] = [];
    items.push({
      label: "属性名称",
      content: attr?.attrName,
    });
    items.push({
      label: "属性编码",
      content: attr?.attrCode,
    });
    items.push({
      label: "单位",
      content: attr?.unit,
    });
    return items;
  };

  // 获取物模型item
  const getSensorItem = (row?: IotDeviceGroup) => {
    if (!row?.sensorGroups) {
      return <Alert theme="warning" title="暂无物模型信息，按需进行添加" />;
    }
    let items: TdDescriptionItemProps[] = [];
    if (row?.sensorGroups) {
      row.sensorGroups?.forEach((sensor: IotSensorGroup) => {
        items.push(...getItems(sensor));
      });
    }
    return (
      <Descriptions
        column={3}
        title="物模型"
        bordered
        labelStyle={{
          width: 200,
          border: "1px solid var(--td-component-border)",
        }}
        itemLayout="vertical"
        contentStyle={{ border: "1px solid var(--td-component-border)" }}
        items={items}
      ></Descriptions>
    );
  };

  const getAttrItems = (row?: IotDeviceGroup) => {
    if (!row?.rltAttrs || row.rltAttrs.length == 0) {
      return <Alert theme="warning" title="暂无属性信息，按需进行添加" />;
    }
    let items: TdDescriptionItemProps[] = [];
    if (row?.rltAttrs) {
      row.rltAttrs?.forEach((attr: IotAttr) => {
        items.push(...getAttrs(attr));
      });
    }
    return (
      <Descriptions
        column={3}
        title="属性信息"
        bordered
        labelStyle={{
          width: 200,
          border: "1px solid var(--td-component-border)",
        }}
        itemLayout="vertical"
        contentStyle={{ border: "1px solid var(--td-component-border)" }}
        items={items}
      ></Descriptions>
    );
  };

  const expandedRow = ({ row }: any) => {
    return (
      <div>
        <div>{getAttrItems(row)}</div>
        <div className="mt-5">{getSensorItem(row)}</div>
      </div>
    );
  };

  return (
    <div className={className}>
      <div className="flex flex-row justify-between mb-4">
        <TableTitle text="产品列表" />
        <Space size={5}>
          {hideAdd ? null : (
            <Button
              onClick={() => {
                setVisible(true);
                setEdit(false);
              }}
            >
              添加产品
            </Button>
          )}
          <Button
            icon={<RefreshIcon />}
            variant="outline"
            onClick={() => {
              getGroupList();
            }}
          ></Button>
        </Space>
      </div>

      <Table<IotDeviceGroup>
        bordered
        columns={[
          {
            align: "left",
            width: 80,
            ellipsis: true,
            colKey: "index",
            title: "序号",
            cell: ({ rowIndex }) => {
              let _index =
                (pageState.pageNum - 1) * pageState.pageSize + rowIndex + 1;
              return <span>{_index}</span>;
            },
          },
          {
            align: "left",
            ellipsis: true,
            colKey: "groupName",
            title: "产品名称",
          },
          {
            align: "center",
            ellipsis: true,
            colKey: "groupCode",
            title: "产品编码(固定编码，勿修改)",
            cell: ({ row }) => {
              return (
                <Tag variant="light-outline" theme="success">
                  {row.groupCode}
                </Tag>
              );
            },
          },

          {
            align: "left",
            ellipsis: true,
            colKey: "groupDesc",
            title: "产品描述",
          },
          {
            align: "center",
            ellipsis: true,
            colKey: "enable",
            title: "是否启用",
            width: 150,
            cell: ({ row }) => {
              return (
                <Switch
                  defaultValue
                  value={row?.isEnable ?? false}
                  onChange={(value) => {
                    apiDeviceGroup.enable(row.id!, value).then(() => {
                      getGroupList();
                      MessagePlugin?.info("操作成功！");
                    });
                  }}
                />
              );
            },
          },
          {
            align: "center",
            fixed: "right",
            width: 300,
            colKey: "op",
            title: "操作",
            cell({ row }) {
              return (
                <>
                  {hideEdit ? null : (
                    <Button
                      theme="success"
                      variant="text"
                      onClick={() => {
                        setVisible(true);
                        setEdit(true);
                        setSelectedRow(row);
                      }}
                    >
                      编辑
                    </Button>
                  )}
                  <Button
                    theme="success"
                    variant="text"
                    onClick={() => {
                      setConfigOpen(true);
                      setSelectedRow(row);
                    }}
                  >
                    配置
                  </Button>
                  {hideDel ? null : (
                    <Popconfirm
                      content="确认删除吗"
                      destroyOnClose
                      placement="top"
                      showArrow
                      theme="default"
                      onConfirm={() => deleteGroup(row.id!)}
                    >
                      <Button theme="primary" variant="text">
                        删除
                      </Button>
                    </Popconfirm>
                  )}
                </>
              );
            },
          },
        ]}
        loading={loading}
        data={userList}
        rowKey="id"
        selectedRowKeys={selectedRowKeys}
        verticalAlign="middle"
        onSelectChange={onSelectChange}
        expandedRow={expandedRow}
        expandedRowKeys={expandedRowKeys}
        onExpandChange={rehandleExpandChange}
        pagination={{
          pageSize: pageState.pageSize,
          total: pageState.total,
          current: pageState.pageNum,
          showJumper: true,
          onCurrentChange(current) {
            setPageState({
              ...pageState,
              pageNum: current,
            });
          },
          onPageSizeChange(size) {
            setPageState({
              ...pageState,
              pageSize: size,
            });
          },
        }}
      />
      <ProductDrawer
        axios={axios}
        open={visible}
        edit={edit}
        value={selectedRow}
        onSuccess={() => {
          setVisible(false);
          getGroupList();
        }}
      />
      <ProductConfigDrawer
        axios={axios}
        open={configOpen}
        edit={edit}
        value={selectedRow}
        onSuccess={() => {
          setConfigOpen(false);
          getGroupList();
        }}
      />
    </div>
  );
};
export default IotProductComp;
